package com.ruihu.admin.module.business.tasknode.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruihu.admin.common.anno.MethodLog;
import com.ruihu.admin.common.constant.JudgeEnum;
import com.ruihu.admin.common.domain.PageResultDTO;
import com.ruihu.admin.common.domain.ResponseDTO;
import com.ruihu.admin.constant.CommonConst;
import com.ruihu.admin.module.business.tasknode.constant.TaskNodeResponseCodeConst;
import com.ruihu.admin.module.business.tasknode.converter.TaskNodeList;
import com.ruihu.admin.module.business.tasknode.dao.TaskNodeDao;
import com.ruihu.admin.module.business.tasknode.domain.dto.*;
import com.ruihu.admin.module.business.tasknode.domain.entity.NodeDefectRelationEntity;
import com.ruihu.admin.module.business.tasknode.domain.entity.TaskNodeEntity;
import com.ruihu.admin.module.business.tasknode.domain.vo.TaskNodeVO;
import com.ruihu.admin.module.business.tasknode.domain.vo.TaskNodeExcelVO;
import com.ruihu.admin.util.PageUtil;
import com.ruihu.admin.util.BeanUtil;
import com.ruihu.admin.util.RequestTokenUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * [ 任务环节 ]
 *
 * @author Tony
 * @version 1.0
 * @company 瑞虎（南京）信息技术有限公司
 * @copyright (c)  瑞虎（南京）信息技术有限公司Inc. All rights reserved.
 * @date 2022-08-30 17:07:35
 * @since JDK1.8
 */
@Service
public class TaskNodeService {

    @Autowired
    private TaskNodeDao taskNodeDao;

    @Autowired
    private NodeDefectRelationService defectRelationService;

    /**
     * 根据id查询
     */
    public TaskNodeEntity getById(Long id) {
        return taskNodeDao.selectById(id);
    }

    /**
     * 分页查询
     *
     * @author Tony
     * @date 2022-08-30 17:07:35
     */
    @MethodLog
    public ResponseDTO<PageResultDTO<TaskNodeVO>> queryByPage(TaskNodeQueryDTO queryDTO) {
        Page page = PageUtil.convert2QueryPage(queryDTO);
        List<TaskNodeDTO> taskNodeDTOList = taskNodeDao.queryByPage(page, queryDTO);
        List<TaskNodeVO> taskNodeVOList = TaskNodeList.convertDTOToTaskNodeVOList(taskNodeDTOList);
        page.setRecords(taskNodeVOList);
        PageResultDTO<TaskNodeVO> pageResultDTO = PageUtil.convert2PageResult(page);
        return ResponseDTO.succData(pageResultDTO);
    }

    /**
     * 添加
     *
     * @author Tony
     * @date 2022-08-30 17:07:35
     */
    @MethodLog
    public ResponseDTO<String> add(TaskNodeAddDTO addDTO) {
        TaskNodeDTO taskNodeDTO = taskNodeDao.queryByTaskNodeName(addDTO.getNodeName());
        if (Objects.nonNull(taskNodeDTO)) {
            return ResponseDTO.wrap(TaskNodeResponseCodeConst.TASK_NODE_NAME_EXISTS);
        }
        TaskNodeDTO taskNodeSortDto = taskNodeDao.queryByTaskSortNo(addDTO.getSortNo());
        if (Objects.nonNull(taskNodeSortDto)) {
            //更新序号
            UpdateWrapper<TaskNodeEntity> warp = new UpdateWrapper<>();
            //通过set设置需要修改的内容，eq设置条件 ,revision = revision+1 .eq("revision", taskNodeSortDto.getRevision())
            warp.setSql("sort_no = sort_no + 1")
                    .ge("sort_no", taskNodeSortDto.getSortNo()).eq("is_delete", "0");
            taskNodeDao.update(null, warp);
        }
        TaskNodeEntity entity = TaskNodeEntity.convertToTaskNodeEntity(addDTO);
        entity.setCreateBy(RequestTokenUtil.getRequestUser().getRequestUserId());
        entity.setCreateTime(new Date());
        entity.setIsDelete(JudgeEnum.NO.getValue().toString());
        entity.setRevision(CommonConst.DEFAULT_OPTI_LOCK_REVISION);
        taskNodeDao.insert(entity);
        //存在该序列
        return ResponseDTO.succ();
    }

    /**
     * 编辑
     *
     * @author Tony
     * @date 2022-08-30 17:07:35
     */
    @MethodLog
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> update(TaskNodeUpdateDTO updateDTO) {
        TaskNodeEntity taskNodeEntity = taskNodeDao.selectById(updateDTO.getId());
        if (Objects.isNull(taskNodeEntity)) {
            return ResponseDTO.wrap(TaskNodeResponseCodeConst.TASK_NODE_NO_EXISTS);
        }
        TaskNodeDTO taskNodeDTO = taskNodeDao.queryByTaskNodeName(updateDTO.getNodeName());
        if (Objects.nonNull(taskNodeDTO) && !Objects.equals(taskNodeDTO.getId(), updateDTO.getId())) {
            return ResponseDTO.wrap(TaskNodeResponseCodeConst.TASK_NODE_NAME_EXISTS);
        }
        /*TaskNodeDTO taskNodeSortDto = taskNodeDao.queryByTaskSortNo(updateDTO.getSortNo());
        if (Objects.nonNull(taskNodeSortDto) && !Objects.equals(taskNodeSortDto.getId(), updateDTO.getId())) {
            return ResponseDTO.wrap(TaskNodeResponseCodeConst.TASK_NODE_HAS_USED);
        }*/
        TaskNodeEntity entity = BeanUtil.copy(updateDTO, TaskNodeEntity.class);
        entity.setRevision(taskNodeEntity.getRevision());
        entity.setUpdateTime(new Date());
        entity.setUpdateBy(RequestTokenUtil.getRequestUser().getRequestUserId());
        taskNodeDao.updateByIdIgnoreEmptyValue(entity);
        return ResponseDTO.succ();
    }

    @MethodLog
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> deleteById(Long taskNodeId) {
        TaskNodeEntity taskNodeEntity = taskNodeDao.selectById(taskNodeId);
        if (Objects.isNull(taskNodeEntity)) {
            return ResponseDTO.wrap(TaskNodeResponseCodeConst.TASK_NODE_NO_EXISTS);
        }
        List<NodeDefectRelationEntity> defectRelationEntityList = defectRelationService.queryByDefectType
                (NodeDefectRelationDTO.builder().taskNodeId(taskNodeId).build());
        if(CollectionUtils.isNotEmpty(defectRelationEntityList)){
            return ResponseDTO.wrap(TaskNodeResponseCodeConst.TASK_NODE_HAS_USED);
        }
        //然后判断节点是否被使用
        taskNodeDao.deleteById(taskNodeId);
        //更新序号
        UpdateWrapper<TaskNodeEntity> warp = new UpdateWrapper<>();
        //通过set设置需要修改的内容，eq设置条件 , revision = revision+1 .eq("revision", taskNodeEntity.getRevision())
        warp.setSql("sort_no = sort_no - 1")
                .ge("sort_no", taskNodeEntity.getSortNo())
                .eq("is_delete", "0");
        taskNodeDao.update(null, warp);
        return ResponseDTO.succ();
    }

    /**
     * 删除
     *
     * @author Tony
     * @date 2022-08-30 17:07:35
     */
    @MethodLog
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> deleteByIds(List<Long> idList) {
        taskNodeDao.deleteByIdList(idList);
        return ResponseDTO.succ();
    }

    /**
     * 查询全部导出对象
     *
     * @author Tony
     * @date 2022-08-30 17:07:35
     */
    @MethodLog
    public List<TaskNodeExcelVO> queryAllExportData(TaskNodeQueryDTO queryDTO) {
        return taskNodeDao.queryAllExportData(queryDTO);
    }

    /**
     * 批量查询导出对象
     *
     * @author Tony
     * @date 2022-08-30 17:07:35
     */
    @MethodLog
    public List<TaskNodeExcelVO> queryBatchExportData(List<Long> idList) {
        return taskNodeDao.queryBatchExportData(idList);
    }

    /**
     * 查询所有任务节点
     * @return
     */
    @MethodLog
    public ResponseDTO<List<TaskNodeVO>> queryTaskNodeList() {
        QueryWrapper<TaskNodeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete","0");
        queryWrapper.orderByAsc("sort_no");
        List<TaskNodeEntity> taskNodeEntityList = taskNodeDao.selectList(queryWrapper);
        List<TaskNodeVO> taskNodeVOList = TaskNodeList.convertEntityToTaskNodeVOList(taskNodeEntityList);
        return ResponseDTO.succData(taskNodeVOList);
    }
}
